<template>
  <div class="main" id="orderForm">
    <div :hidden="!created">
      <IndentState :indentState="indentState" :fontSize="40"/>
    </div>

    <div class="air-column">
      <el-descriptions :title="hotel.name" :column="4">
        <el-descriptions-item label="房间类型">{{ roomType.type }}</el-descriptions-item>
        <el-descriptions-item label="可住人数">{{ roomType.capacity }}人</el-descriptions-item>
        <el-descriptions-item label="床型">{{ roomType.bedType }}</el-descriptions-item>
        <el-descriptions-item label="早餐">
          <el-tag size="small">{{ hasBreakfast(roomType.breakfast) }}</el-tag>
        </el-descriptions-item>

      </el-descriptions>
    </div>

    <div class="air-column">
      <el-descriptions :title="'预订信息'" :column="4">
        <el-descriptions-item label="入住时间" id="checkinform"><el-date-picker
            class="input-with-select"
            v-model="checkInTime"
            type="datetime"
            placeholder="选择日期时间"
            :disabled="created"
        >
        </el-date-picker>
        </el-descriptions-item>

        <el-descriptions-item label="退房时间" id="checkoutform">
          <el-date-picker
              class="input-with-select"
              v-model="checkOutTime"
              type="datetime"
              placeholder="选择日期时间"
              :disabled="created"
          >
          </el-date-picker>
        </el-descriptions-item>

        <el-descriptions-item label="房间数量" id="roomnumform"><el-input-number
            class="input-with-select"
            v-model="roomNum"
            @change="handleChange"
            :min="1"
            :max="10"
            :disabled="created"
        ></el-input-number>
        </el-descriptions-item>
      </el-descriptions>
    </div>


    <el-row
        type="flex"
        justify="space-between"
        align="middle"
        class="info-bar"
    >
      <span>应付总额：</span>
      <span class="price">￥ {{getTotalAmount(checkInTime,checkOutTime,roomNum,roomType.amount)}}</span>
    </el-row>
    <div :hidden="created"><el-button type="warning" class="submit" @click="handleSubmit"
    >asd</el-button
    ></div>
    <div  :hidden="!((created&&(!paid)))">
      <el-button type="warning" class="submit" @click="handlePayment">确认支付</el-button>
      <el-button type="warning" class="submit" @click="handleCancel">取消订单</el-button>
      <div>订单将在{{countdownstring}}后过期，请尽快支付</div>
      <!--          <CountDown :endTime="endTime" :callback="''" :endText="'订单已超时取消'"/>-->
    </div>



  </div>
</template>

<script setup lang="ts">
import {ref, getCurrentInstance, onMounted,defineProps} from "vue"
import IndentState from "./IndentState.vue";
import {alertProps} from "element-plus";
import axios from "axios";
const { proxy }=getCurrentInstance()

// Hotel info: { hotelId, name }
// Room type: { amount, bed type, type, breakfast, capacity }
// User info: { user_id }
const getTotalAmount=(checkInTime,checkOutTime,roomNum,amount)=>{
  // return 0
  if(checkInTime==""||checkOutTime=={}||JSON.stringify(checkInTime) == "{}"||JSON.stringify(checkOutTime) == "{}"){
    return 0
  }
  else{
    return  amount*roomNum *(checkOutTime-checkInTime)/3600/24/1000
  }
}
const endText=ref("")
const callback=ref("")
const countdownstring=ref("")
const totalAmount=ref(0)
const endTime =ref(0)
const props = defineProps({
  hotel: {
    type: Object,
    default: {
      id: 1297,
      name: "HOTELNAME"
    },
  },
  roomType: {
    type: Object,
    default: {
      id:1,
      bedType: "BEDTYPE",
      type: "ROOMTYPE",
      amount: 0.0,
      breakfast: 0,
      capacity: 0,
    },
  },
  user: {
    type: Object,
    default: {
      user_id: 0
    },
  },
})
const buttonInfo=ref("提交订单")
const indentState=ref("")
const checkInTime=ref({})
const checkOutTime=ref({})
const roomNum=ref(0)
const customerName=ref("AMY")
const customerPhone=ref("13435258593")
const created=ref(false)
const paid =ref(false)
const createIndentBatchAO={
  hotelId:0,
  roomTypeId:0,
  roomNum:0,
  checkInTime:"0000-00-00 00:00:00",
  checkOutTime:"1111-11-11 11:11:11",
  customer:{
    customerName:"AMY",
    customerPhone:"123"
  }
}
const createIndentBatchVO=ref({
  batchId:0,
  indentBatchGenerationTime:0,
})

// const hotel=ref([])
// const room_type=ref([])
// const indentBatchVO=ref([])

// onMounted(()=>{
//   console.log("HEREISHOTEL")
//     console.log()
//       proxy.$http.get(
//          '/api/hotel?id='+hotelId
//          //  '/api/hotel?id=1297'
//       ).then(res=>{
//         console.log("HEREISHOTEL")
//         console.log(res)
//         console.log("HEREISHOTEL")
//       })
//     }
// )

// const hotel = ref({
//   name: "HOTELNAME",
// })
// const room_type = ref({
//   type: "VIPROOM",
//   bedType: "BIGBED",
//   capacity: 2,
//   breakfast: 1,
// })
// const indentBatchVO=ref({
//   indentBatch:[{
//     indentState:"CREATED",
//     checkInTime:new Date(),
//     checkOutTime:new Date(),
//
//   }],
//   totalAmount:0,
// })

const timeFormat = (mystime)=>{
  var addstime = mystime.getFullYear() +'-'  + fullNum(Number(mystime.getMonth()) + 1)+ '-'
      + fullNum(mystime.getDate())+ ' '+ fullNum(mystime.getHours())+ ":"
      + fullNum(mystime.getMinutes()) + ":" +fullNum(mystime.getSeconds());
  return addstime;

}
const fullNum=(obj)=>{
  if(Number(obj)<10){
    return '0'+obj;
  }else{
    return obj;
  }

}
const hasBreakfast =(b: Number) => {
  if(b==0)return '不含早餐'
  else return '含早餐'
}
let self = this
const handleSubmit = () => {
  createIndentBatchAO.hotelId = props.hotel.id
  createIndentBatchAO.roomTypeId = props.roomType.id
  createIndentBatchAO.roomNum = roomNum.value
  createIndentBatchAO.checkInTime = timeFormat(checkInTime.value)
  createIndentBatchAO.checkOutTime = timeFormat(checkOutTime.value)
  createIndentBatchAO.customer.customerName = customerName.value
  createIndentBatchAO.customer.customerPhone = customerPhone.value
  // console.log("HERE IS AO!!")
  // console.log(createIndentBatchAO)
  proxy.$http.post(
      '/api/indent/batch',
      createIndentBatchAO,
  ).then(res => {

    createIndentBatchVO.value.indentBatchGenerationTime = res.data.data.indentBatchGenerationTime
    createIndentBatchVO.value.batchId = res.data.data.batchId
    let tempstring = Math.floor(createIndentBatchVO.value.indentBatchGenerationTime / 1000 + 30 * 60).toString()
    endTime.value = Number(tempstring)
    // alert(createIndentBatchVO.value.indentBatchGenerationTime)
    // alert(endTime.value)

    countdown(endTime.value,handleCancel)
  })
  created.value = true
  indentState.value = "CREATED"

}
const handleCancel=()=>{
  indentState.value="CANCELED"
  paid.value=true
  proxy.$http.delete(
      // axios.patch('http://localhost:8080'+
      '/api/indent/batch?batchId='+createIndentBatchVO.value.batchId,
  ).then(res=>{})

}
const handlePayment = ()=>{
  proxy.$http.patch(
      // axios.patch('http://localhost:8080'+
      '/api/indent/batch?batchId='+createIndentBatchVO.value.batchId,
  ).then(res=>{})
  paid.value=true
  indentState.value="PAID"
}


const countdown=(timestamp,_callback)=>{
  // alert("thisistimestamp")
  // alert(timestamp)
  let self = this;
  let timer = setInterval(function(){
    let nowTime = new Date();
    let endTime = new Date(timestamp * 1000);
    let t = endTime.getTime() - nowTime.getTime();
    if(t>0){
      let day = Math.floor(t/86400000);
      let hour=Math.floor((t/3600000)%24);
      let min=Math.floor((t/60000)%60);
      let sec=Math.floor((t/1000)%60);
      let shour = hour < 10 ? "0" + hour : hour;
      let smin = min < 10 ? "0" + min : min;
      let ssec = sec < 10 ? "0" + sec : sec;
      let format = '';
      if(day > 0){
        format =  `${day}天${shour}小时${smin}分${ssec}秒`;
      }
      if(day <= 0 && hour > 0 ){
        format = `${shour}小时${smin}分${ssec}秒`;
      }
      if(day <= 0 && hour <= 0){
        format =`${smin}分${ssec}秒`;
      }
      countdownstring.value=format
      // console.log("!!!!")
      // console.log(format)

    }else{
      clearInterval(timer);
      countdownstring.value = endText.value;
      // alert("STYPID")
      if(paid==false){
        self._callback();
      }

    }
  },1000);
}
const _callback=()=> {
  if (this.callback && this.callback instanceof Function) {
    this.callback(...this);
  }
}




</script>

<style>
.air-column {
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px #ddd dashed;
}
h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

.info-bar {
  border-top: 1px #ddd dashed;
  padding: 10px 15px;
  font-size: 14px;
  color: #666;
}
.price {
  font-size: 28px;
  color: orange;
}
.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}



</style>
